package lucene.server.web.dao;



import lombok.extern.slf4j.Slf4j;
import lucene.server.common.datasource.PooledDataSource;
import lucene.server.common.dbmeta.ColumnMeta;
import lucene.server.common.dbmeta.DBMetaUtil;
import lucene.server.common.utils.DatabaseUtil;
import lucene.server.common.utils.TypeUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class DynamicDao {

    public static ConcurrentHashMap<String,List<ColumnMeta>> columnMap = new ConcurrentHashMap<>();

    public static String getCatalog(String connName) {
        PooledDataSource datasource = null;
        String databaseName = "";
        try {
            datasource = DynamicDataSource.getDataSource(connName);
            databaseName =  datasource.getConnection().getCatalog();
        } catch (SQLException e) {
            log.error("获取表信息失败",e);
        }finally {
            datasource.release();
        }
        return databaseName;
    }
    public static List<String> getTables(String connName) {
        List<String> tableNames = new java.util.ArrayList<>();
        PooledDataSource datasource = null;
        ResultSet tables = null;
        try {
            datasource = DynamicDataSource.getDataSource(connName);
            DatabaseMetaData metaData = datasource.getConnection().getMetaData();
            String databaseName =  datasource.getConnection().getCatalog();
            tables = metaData.getTables(databaseName, null, "%", new String[]{"TABLE"});
            while (tables.next()) {
                tableNames.add( tables.getString("TABLE_NAME"));
            }
        } catch (SQLException e) {
             log.error("获取表信息失败",e);
        }finally {
            datasource.release();
            DatabaseUtil.close(tables);
        }
        return tableNames;
    }

    public static List<ColumnMeta> getFields(String connName,String tableName,boolean dealLob)
    {
        if (columnMap.containsKey(connName+"::"+tableName)){
            return columnMap.get(connName+"::"+tableName);
        }
        List<ColumnMeta> columns = new ArrayList<>();

        PooledDataSource datasource = null;
        try {
            datasource = DynamicDataSource.getDataSource(connName);
            DatabaseMetaData metaData = datasource.getConnection().getMetaData();
            String databaseName = datasource.getConnection().getCatalog();
            columns = DBMetaUtil.getTableColumns(metaData,databaseName,tableName);

        }catch (Exception exception){
            log.error("获取字段信息失败",exception);
        }finally {
            datasource.release();
            DatabaseUtil.close(columns);
        }
        columnMap.put(connName+"::"+tableName,columns);
        return  columns;
    }


}
